<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class AuthService extends CI_Controller
{

	//Doctrine EntityManager
	public $em;

	function __construct()
	{
 		parent::__construct();

  		//Not required if you autoload the library
 		$this->load->library('doctrine');

  		//Instantiate a Doctrine Entity Manager
 		$this->em = $this->doctrine->em;
 	}
	
	public function index()
	{
		die("index");
		$user = new models\User;
		$user->setUsername('Joseph');
		$user->setPassword('Password');		
		$this->em->persist($user);
		$this->em->flush(); 
	}
	
	public function login(){
		//var_dump(models\service\CurrentUser::login($this->input->post('username'), $this->input->post('password')));
		
		if (models\service\CurrentUser::login($this->input->post('username'), $this->input->post('password')) === FALSE){
			//echo ">>" . models\service\CurrentUser::getErrorMessage();
			$this->session->set_userdata('flash_message',models\service\CurrentUser::getErrorMessage());
			header('location: '.base_url());
		} else {
			$user = models\service\CurrentUser::user();
			$home = $this->getHome($user);
			header('location: '.$home);		
		}		
	}	
	
	public function getHome($user){
		$criteria = array('userId' => $user->getUserId());
		$userProfiles = $this->em->getRepository('\models\entities\UserProfile')->findBy($criteria);
		foreach ($userProfiles as $p){
			if ($p->getProfile()->getMenuInbox() != ""){
				//return base_url().'inbox/profile/'.$userProfiles[0]->getProfile()->getId();
			/*	if ($userProfiles[0]->getProfile()->getId() == 6 || $userProfiles[0]->getProfile()->getId() == 10){
					return base_url().'inbox/dashboard/';
				} else {
					return base_url().'inbox/profile/'.$userProfiles[0]->getProfile()->getId();	
				} */
				if ($userProfiles[0]->getProfile()->getId() != 6){
					return base_url().'dashboard/manager';
				} else {
					//return base_url().'inbox/profile/'.$userProfiles[0]->getProfile()->getId();
					return base_url().'dashboard/managerCf';
				}
				// return base_url().'inbox/sentBerkas/'.$userProfiles[0]->getProfile()->getId();
			} 
			if ($p->getProfile()->getNamaProfile()=="ADMINISTRATOR"){
				return base_url().'administration/userList';
			}
		}
		
		return base_url().'report/rekapLaporan';
	}
	
	public function logout(){
		$this->session->userdata = array();
        $this->session->sess_destroy();
        header('location: '.base_url());		
	}
	
	public function goHome(){
		$user = models\service\CurrentUser::user();
		$home = $this->getHome($user);
		header('location: '.$home);
	}
}